<?php

namespace app\admin\controller;

use think\Controller;

class Common extends Controller {

        public function _initialize() {
                //手动分离字段缓存和数据缓存
                //初始化禁止request抓取cookie修复tp框架问题非常重要
                $_REQUEST = array_merge($_GET, $_POST);

                //检查是否登录
                if (!get_member_id()) {
                        if (IS_AJAX) {
                                $this->noAccess('登录超时，请刷新页面重新登陆');
                        } else {
                                $this->redirect("login/login");
                        }
                }

                /*
                 * @ 访问权限检查
                 * @ strtolower 小写转化
                 * @ CONTROLLER_NAME 当前控制器名 
                 * @ ACTION_NAME 当前操作名  
                 */
                $rule = strtolower(CONTROLLER_NAME . '/' . ACTION_NAME);
                if (!$this->checkRule($rule) && get_member_id() != 1) {
                        $this->noAccess('您可能没有权限！');
                }

                /**
                 * 检查用户组
                 */
                $access_id = M("AuthGroupAccess")->where(array('uid' => get_member_id()))->getField("group_id");
                $this->assign('access_id', $access_id);
        }

        /**
         * 权限检测
         * @param string  $rule    检测的规则
         * @param string  $mode    check模式
         * @return boolean
         */
        final protected function checkRule($rule, $mode = 'url') {
                static $Auth = null;
                if (!$Auth) {
                        $Auth = new \org\Auth();
                }
                if (!$Auth->check($rule, get_member_id(), $type = 1, $mode)) {
                        return false;
                }
                return true;
        }

        /**
         * 检查用户是否登录
         * @return integer UID
         */
        protected function checkUser() {
                $mid = get_member_id();
                if ($mid > 0) {
                        return $mid;
                } else {
                        $this->redirect("Login/login");
                }
        }

        /**
         * 无权限
         * @param type $msg
         */
        protected function noAccess($msg = "请重新登陆") {
                $info['message'] = $msg;
                $info['statusCode'] = 300;
                $this->ajaxReturn($info);
        }

        /**
         * Ajax方式返回数据到客户端
         * @access protected
         * @param mixed $data 要返回的数据
         * @param String $type AJAX返回数据格式
         * @param int $json_option 传递给json_encode的option参数
         * @return void
         */
        protected function ajaxReturn($data, $type = '', $json_option = 0) {
                if (empty($type))
                        $type = C('DEFAULT_AJAX_RETURN');
                switch (strtoupper($type)) {
                        case 'JSON' :
                                // 返回JSON数据格式到客户端 包含状态信息
                                header('Content-Type:application/json; charset=utf-8');
                                exit(json_encode($data, $json_option));
                        case 'XML' :
                                // 返回xml格式数据
                                header('Content-Type:text/xml; charset=utf-8');
                                exit(xml_encode($data));
                        case 'JSONP':
                                // 返回JSON数据格式到客户端 包含状态信息
                                header('Content-Type:application/json; charset=utf-8');
                                $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                                exit($handler . '(' . json_encode($data, $json_option) . ');');
                        case 'EVAL' :
                                // 返回可执行的js脚本
                                header('Content-Type:text/html; charset=utf-8');
                                exit($data);
                        default :
                                // 用于扩展其他返回格式数据
                                Hook::listen('ajax_return', $data);
                }
        }

        /**
          +----------------------------------------------------------
         * 根据表单生成查询条件
         * 进行列表过滤
          +----------------------------------------------------------
         * @access protected
          +----------------------------------------------------------
         * @param string $name 数据对象名称
          +----------------------------------------------------------
         * @return HashMap
          +----------------------------------------------------------
         * @throws ThinkExecption
          +----------------------------------------------------------
         */
        protected function _search($name = '') {
                //生成查询条件
                if (empty($name)) {
                        $name = $this->getActionName();
                }
                $model = D($name);
                $map = array();
                foreach ($model->getFields() as $val) {
                        if (isset($_REQUEST[$val]) && $_REQUEST[$val] != '') {
                                $map[$val] = $_REQUEST[$val];
                        }
                }
                return $map;
        }

        /**
          +----------------------------------------------------------
         * 根据表单生成查询条件
         * 进行列表过滤
          +----------------------------------------------------------
         * @access protected
          +----------------------------------------------------------
         * @param Model $model 数据对象
         * @param HashMap $map 过滤条件
         * @param string $sortBy 排序
         * @param boolean $asc 是否正序
          +----------------------------------------------------------
         * @return void
          +----------------------------------------------------------
         * @throws ThinkExecption
          +----------------------------------------------------------
         */
        protected function _list($model, $map = array(), $sortBy = '', $asc = false, $relation = false, $group = false, $table = "") {
                //排序字段 默认为主键名
                if (!empty($_REQUEST['orderField'])) {
                        $order = $_REQUEST['orderField'];
                } else {
                        $order = !empty($sortBy) ? $sortBy : $model->getPk();
                }
                //排序方式默认按照倒序排列
                //接受 sost参数 0 表示倒序 非0都 表示正序
                if (isset($_REQUEST['orderDirection'])) {
                        $sort = $_REQUEST['orderDirection'] == 'asc' ? 'asc' : 'desc';
                } else {
                        $sort = $asc ? 'asc' : 'desc';
                }
                //取得满足条件的记录数
                $count = $model->where($map)->count();
                if ($count > 0) {
                        //创建分页对象
                        if (!empty($_REQUEST['pageSize'])) {
                                $listRows = $_REQUEST['pageSize'];
                        } else {
                                $listRows = 20;
                        }
                        $p = new \org\Page($count, $listRows);
                        //分页查询数据
                        if (!empty($table)) {
                                $model->table($table . " a");
                        }
                        $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows);
                        if ($relation !== false) {
                                $model->relation($relation);
                        }
                        if ($group !== false) {
                                $model->group($group);
                        }
                        $voList = $model->select();

                        //分页跳转的时候保证查询条件
                        foreach ($map as $key => $val) {
                                if (!is_array($val)) {
                                        $p->parameter[$key] = urlencode($val);
                                }
                        }
                        //模板赋值显示
                        $this->assign("orderField", $order);
                        $this->assign("orderDirection", $sort);
                        $this->assign('list', $voList);
                        $this->assign('totalCount', $count);
                        $this->assign('numPerPage', $p->listRows);
                        $this->assign('currentPage', !empty($_REQUEST[C('VAR_PAGE')]) ? $_REQUEST[C('VAR_PAGE')] : 1);
                } else {

                        $this->assign("orderField", '');
                        $this->assign("orderDirection", '');
                        $this->assign('list', '');
                        $this->assign('totalCount', '0');
                        $this->assign('numPerPage', '20');
                        $this->assign('currentPage', '1');
                }
        }

        /**
         * 插入数据
         * @param type $name 模型名
         * @param type $validates 是否验证
         * @param type $autos 是否填充
         * @param type $dorm 是否使用D
         */
        protected function _insert($name, $validates = true, $autos = true, $dorm = false) {
                if ($dorm == true) {
                        $model = D($name);
                } else {
                        $model = M($name);
                }
                $name_low = strtolower($name) . '.add';
                //验证
                if ($validates == true) {
                        $validate = \think\Loader::validate($name);
                        if (!$validate->scene('add')->check($_REQUEST)) {
                                return $this->iError($validate->getError());
                        }
                }
                if ($autos == true) {
                        $result = $model->auto($name_low)->create();
                } else {
                        $result = $model->create();
                }
                if (!$result) {
                        return $this->iError($model->getError());
                } else {
                        $list = $model->add();
                }
                if ($list !== false) {
                        $this->sysAdd("执行了【" . getaction() . "】添加操作，id=" . $list);
                        return $this->iSucess('新增成功');
                } else {
                        //失败提示
                        return $this->iError('新增失败!');
                }
        }

        /**
         * 更新数据
         * @param type $name 模型名
         * @param type $validates 是否验证
         * @param type $autos 是否填充
         * @param type $dorm 是否使用D
         */
        protected function _update($name, $validates = true, $autos = true, $dorm = false) {
                if ($dorm == true) {
                        $model = D($name);
                } else {
                        $model = M($name);
                }
                $name_low = strtolower($name) . '.edit';
                //验证
                if ($validates == true) {
                        $validate = \think\Loader::validate($name);
                        if (!$validate->scene('edit')->check($_REQUEST)) {
                                return $this->iError($validate->getError());
                        }
                }
                //填充
                if ($autos == true) {
                        $result = $model->auto($name_low)->create();
                } else {
                        $result = $model->create();
                }
                if (!$result) {
                        return $this->iError($model->getError());
                } else {
                        // 更新数据
                        $pk = $model->getPk();
                        $id = $_REQUEST[$pk];
                        $list = $model->where(array($pk => $id))->save();
                }
                if (false !== $list) {
                        $this->sysAdd("执行了【" . getaction() . "】编辑操作，id=" . $id);
                        return $this->iSucess('编辑成功');
                } else {
                        //失败提示
                        return $this->iError('编辑失败!');
                }
        }

        /**
         * 删除数据
         * @param type $name 模型名
         */
        protected function _delete($name, $id) {
                $model = M($name);
                if (!empty($model)) {
                        $pk = $model->getPk();
                        if (isset($id)) {
                                $condition = array($pk => array('in', explode(',', $id)));
                                if (false !== $model->where($condition)->delete()) {
                                        $this->sysAdd("执行了【" . getaction() . "】删除操作，id=" . $id);
                                        return $this->delSuccess('删除成功');
                                } else {
                                        return $this->iError('删除失败！');
                                }
                        } else {
                                return $this->iError('非法操作');
                        }
                }
        }

        /*
         * 返回doajax删除信息
         */

        protected function delSuccess($data) {
                $datas = array();
                $datas['message'] = $data;
                $datas['statusCode'] = '200';
                $this->ajaxReturn($datas);
        }

        /*
         * 不执行刷新成功
         */

        protected function iSucess($data) {
                $datas = array();
                $datas['message'] = $data;
                $datas['statusCode'] = '200';
                if (!empty($_REQUEST['navTabname'])) {
                        $datas['tabid'] = $_REQUEST['navTabname'];
                }
                $datas['closeCurrent'] = true;
                $this->ajaxReturn($datas);
        }

        /*
         * 不执行刷新失败
         */

        protected function iError($data) {
                $datas = array();
                $datas['message'] = $data;
                $datas['statusCode'] = '300';
                $this->ajaxReturn($datas);
        }

        /**
         * systemLog 不执行add方法而改执行以下方法
         * @param string  $msg     
         */
        protected function sysAdd($msg) {
                $ip = new \org\iplocation\IpLocation('UTFWry.dat');
                $area = $ip->getlocation();
                $mid = get_member_id();
                $username = M("Member")->where(array('id' => $mid))->getField('realname');
                $data = array(
                    'mid' => get_member_id(),
                    'username' => $username,
                    'content' => $msg,
                    'ip' => $area['ip'],
                    'ip_city' => $area['country'],
                    'create_time' => time()
                );
                if (!empty($msg)) {
                        M('SystemLog')->add($data);
                }
        }

        /**
         * 上传图片
         * @param type $file 上传文件
         * @param type $path 保存路径
         */
        protected function _uploadImage($file, $config, $thumb = array()) {
                $upload = new \org\Upload($config);
                $info = $upload->uploadOne($file);
                //缩略图
                if (!empty($thumb)) {
                        $imageLib = new \org\Image();

                        $thumbWidth = explode(',', $thumb['maxWidth']);
                        $thumbSuffix = explode(',', $thumb['suffix']);
                        $thumbDelete = $thumb['picDelete'];

                        for ($i = 0, $len = count($thumbWidth); $i < $len; $i++) {
                                $thumbname = basename($info['savename'], '.' . $info['ext']) . $thumbSuffix[$i];
                                $imageLib::open('./Uploads/' . $info['savepath'] . $info['savename']);
                                $imageLib::thumb($thumbWidth[$i], $thumbWidth[$i]);
                                $imageLib::save('./Uploads/' . $info['savepath'] . $thumbname . '.' . $info['ext']);
                                $info['thumb'][] = $info['savepath'] . $thumbname . '.' . $info['ext'];
                        }

                        if ($thumbDelete) {
                                unlink('.' . '/Uploads/' . $info['savepath'] . $info['savename']);
                        }
                }

                if ($info !== false) {
                        return $info;
                } else {
                        return false;
                }
        }


}
